package com.rongchuang.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.rongchuang.dto.CompanyDTO;
import com.rongchuang.entity.Company;
import com.rongchuang.entity.QCompany;
import com.rongchuang.repository.CompanyRepository;
import com.rongchuang.util.ConverterUtil;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CompanyService {

    @Autowired
    private CompanyRepository companyRepository;

    @Autowired
    private JPAQueryFactory queryFactory;

    /**
     * 保存企业信息
     */
    public void modify(CompanyDTO companyDTO) {
        Company company = ConverterUtil.convertTo(companyDTO, Company.class);
        companyRepository.save(company);
    }

    /**
     * 分页查询
     */
    public Page<CompanyDTO> pageSearch(int pageNum, int pageSize, String name) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        QCompany company = QCompany.company;
        BooleanBuilder builder = new BooleanBuilder();
        if (StringUtils.isNotBlank(name)) {
            builder.and(company.name.eq(name));
        }
        List<Company> companies = queryFactory
                .selectFrom(company)
                .where(builder)
                .offset((long) pageNum * pageSize)
                .limit(pageSize)
                .orderBy(company.id.desc())
                .fetch();
        long total = queryFactory
                .selectFrom(company)
                .where(builder)
                .fetchCount();
        List<CompanyDTO> companyDTOS = ConverterUtil.convertToList(companies, CompanyDTO.class);
        return new PageImpl<>(companyDTOS, pageable, total);
    }

    /**
     * 获取企业详情
     * @param id 商会id
     */
    public CompanyDTO getDetail(Long id) {
        Company company = companyRepository.getById(id);
        return ConverterUtil.convertTo(company, CompanyDTO.class);
    }
}
